const mongoose = require('mongoose');
const _ = require("lodash");
const { User, Device } = require('./Schema');
const Items = require("ajv/lib/vocabularies/applicator/items");
// 连接数据库
mongoose.connect('mongodb://192.168.252.249:27017/zrl', 
    //{ useNewUrlParser: true, useUnifiedTopology: true }
)
    .then(() => console.log('MongoDB connected'))
    .catch(err => console.error('MongoDB connection error:', err));

// mongoose.connection.on(('error',(e)=>{
//   console.log('monngo连接失败', e);
// }))

const status = new mongoose.Schema({
    name: String,
    description: String
});
const Item = mongoose.model('Item', status);
//删除
// Item.deleteOne({ name: '字符串' });

//表查询
const queryFindData = async () => {
    //   const ret = await Item.find({name:'字符串'}); //条件查询
    //   const ret = await User.find({name:{ $regex: 'John', $options: 'i' }}); //条件查询
    //   const id = await Item.findById("67abf8a4228003013dfd5a6c"); //查询id
    //   const list = await Item.find(); //查询所有数据
    //   console.log('查询结果', ret);
    //   console.log('id查询结果', id);
    //const posts = await User.find().populate('author'); //多表查询
    const item = await User.find().populate({  //多层嵌套
        path: 'author',
        populate: {
            path: 'user',
        }
    })
    //$lt(小于)  $lte(小于等于)   $gt(大于)  $gte(大于等于)   $ne(不等于)
    //const list = await User.find({ age: { $gt: 17, $lt: 66 } }).populate('author');
    //
    //const a = list.equals(ret); //比较俩者ID是否相同
    //const users = await User.find().skip((page - 1) * pageSize).limit(pageSize); //分页查询

    const list = await User.findOne({_id:"67abf8a4228003013dfd5a6c"}, { deviceName: 1}).populate('author'); //只返回该字段
    console.log('查询结果', list);
}
//queryFindData();


//更新数据
const queryUpdate = async () => {
    //const _id = new mongoose.Types.ObjectId('1'.repeat(24));
    //  const _id = '67abf8a4228003013dfd5a6c';
    //   console.log('id的值',_id);
    //   const result = await Item.findByIdAndUpdate(_id,{name:"更新字符串546"},{new: true});
    //   console.log('更新成功', result);
    const result = await User.findByIdAndUpdate("67ac12762c9f523126e9b710", { name: "更新用户的名字" }, { new: true });
    // const result = await User.updateMany(
    //     { age: { $gt: 30, $lt:30 } },
    //     { name: "跟新"}
    // );
    console.log('更新数据成功', result);
}
//queryUpdate();
//删除数据
const querydelete = async () => {

    //Device.collection.drop(); //删除表

    //const result = await User.findByIdAndDelete("67ac1d1cdf3b15a67634193d");
    //   const result = await User.deleteOne({ name: "z41556" });
    //   console.log('删除成功', result);
    /* 
     删除相关联表
    */
    const list = await User.find({ $and: [{ name: "z41556" }] })
    if (list.length === 0) {
        console.log('No users found with the specified name.');
        return;
    }
    const ids = _.map(list, 'author');
    console.log('数组', ids);
    const [deleteUserResult, deletePostResult] = await Promise.all([
        User.deleteMany({ _id: { $in: ids } }),
        Device.deleteMany({ _id: { $in: ids } })
    ]);
}
//querydelete();

//创建数据
const queryAdd = async () => {
    //const data = await Item.create({"name":"添加数据",description:"数字"});
    const device = await Device.create({
        deviceName: "设备名称45",
    })
    const user = await User.create([{
        name: 'z41556',
        age: 85,
        email: "1586459885@qq.com",
        password: "123456",
        role: "1",
        status: "1",
        author: device._id,
    }])
    console.log('添加数据成功', user);
    console.log('表数据插入成功');
}

//queryAdd();

// const nestedSchema = new mongoose.Schema(
//   { name: String },
//   { _id: false } // <-- disable `_id`
// );
// const schema = new mongoose.Schema({
//   subdoc: nestedSchema,
//   docArray: [nestedSchema]
// });
// const Test = mongoose.model('Test', schema);

// Neither `subdoc` nor `docArray.0` will have an `_id`
// await Test.create({
//   subdoc: { name: 'test 1' },
//   docArray: [{ name: 'test 2' }]
// });



